package middleware

import (
	"fmt"
	"time"

	"gitee.com/clearluo/gotools/util/qps"

	"github.com/google/uuid"

	"gitee.com/clearluo/gotools/zaplog"
	"github.com/gin-gonic/gin"
)

var (
	qpsObj = qps.NewQPS()
)

func init() {
	go qpsObj.Start()
}

// 日志记录到文件
func LoggerToFile() gin.HandlerFunc {
	return func(c *gin.Context) {
		qpsObj.Add()
		// 开始时间
		startTime := time.Now()
		reqNo := uuid.New().String()
		zaplog.Infof("|%35v|", reqNo)

		// 处理请求
		c.Next()

		// 结束时间
		endTime := time.Now()

		// 执行时间
		latencyTime := endTime.Sub(startTime)

		// 请求方式
		reqMethod := c.Request.Method

		// 请求路由
		reqUri := c.Request.RequestURI

		// 状态码
		statusCode := c.Writer.Status()

		// 请求IP
		clientIP := c.ClientIP()

		// 日志格式
		zaplog.Infof("|%35v| %3d | %13v | %15s | %s | %s |",
			reqNo,
			statusCode,
			latencyTime,
			clientIP,
			reqMethod,
			reqUri,
		)
	}
}

var CustomLogFormatter = func(param gin.LogFormatterParams) string {
	var statusColor, methodColor, resetColor string
	if param.IsOutputColor() {
		statusColor = param.StatusCodeColor()
		methodColor = param.MethodColor()
		resetColor = param.ResetColor()
	}
	if param.Latency > time.Minute {
		// Truncate in a golang < 1.8 safe way
		param.Latency = param.Latency - param.Latency%time.Second
	}
	return fmt.Sprintf("%v [GIN] xx.go|%s %3d %s| %13v | %15s |%s %-7s %s %#v\n%s",
		param.TimeStamp.Format("[2006-01-02 15:04:05.000 MST]"),
		statusColor, param.StatusCode, resetColor,
		param.Latency,
		param.ClientIP,
		methodColor, param.Method, resetColor,
		param.Path,
		param.ErrorMessage,
	)
}
